from flask import Blueprint, request, render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required
from app.services.auth_service import AuthService
from app.models.user import User

bp = Blueprint('auth', __name__)
auth_service = AuthService()

@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        email = request.form.get('email')
        phone = request.form.get('phone')
        nickname = request.form.get('nickname')
        
        if not username or not password:
            flash('用户名和密码不能为空')
            return render_template('auth/register.html')
        
        success, message = auth_service.register(username, password, email, phone, nickname)
        if success:
            flash('注册成功，请登录')
            return redirect(url_for('auth.login'))
        else:
            flash(message)
            return render_template('auth/register.html')
    
    return render_template('auth/register.html')

@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        if not username or not password:
            flash('用户名和密码不能为空')
            return render_template('auth/login.html')
        
        user, message = auth_service.login(username, password)
        if user:
            login_user(user)
            return redirect(url_for('index'))
        else:
            flash(message)
            return render_template('auth/login.html')
    
    return render_template('auth/login.html')

@bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))